<?php
namespace Com\Pay;

//趣讯支付宝扫码支付

class QuxunPay{

    private $config = array();

    public function __construct($mchData){
        $this->config = $mchData;
    }

    /*生成支付连接*/
    public function getUrl($order_info){
        $merchantCode = $this->config['mch_id'];
        $notifyUrl = S_URL . '/Api/NotifyCallback/QuxunPayNotify';
        $order_sn = $order_info['ordernumber'];
        $price = $order_info['paymoney'];
        $post_data = array(
            "appKey" => $merchantCode,
            'notifyUrl' => $notifyUrl,
            'bussOrderNum' => $order_sn,
            'payMoney' => $price,
            'orderName' => "CBPAY",
            'remark' => $this->config['mch_id'],
            'channel' => $order_info['channel'],
            'returnUrl' => $order_info['return_url'],
        );
        $post_data['sign'] = $this->getSign($post_data , $this->config['mch_key']);

        $str = "";
        // 字符串传递
        foreach($post_data as $key1=>$val)  {
            $str.=$key1."=".$val."&";
        }
        $str = rtrim($str,'&');
        // 字符串传递 The End

        $Send_url = 'https://pay.iquxun.cn/aiJinFuPay/aliScanPay.do';
        $result = json_decode(https_request($Send_url , array("paramStr" => $str)) , true);
        if($result['resultCode'] == '200'){
            return $result['Data']['qr_code'];
        }
        return '';
    }

    private function getSign($arr,$keyValue){
        $string = 'keyValue='.$keyValue.'&'.$this->getParamStr($arr);
        $sign=md5(strtoupper($string));
        return $sign;
    }

    private function getParamStr($arr){
        $string='';
        ksort($arr);
        //拼接不需要uncode  不用http_build_query()；
        $count = count ( $arr );
        $i = 0;
        foreach ( $arr as $k => $v ) {
            if ($i < $count - 1) {
                $string .= $k . '=' . $v . '&';
            } else {
                $string .= $k . '=' . $v;
            }
            $i ++;
        }
        return $string;
    }

    private function checkSign($arr,$keyValue){
        $sign = $arr['sign'];
        unset($arr['sign']);
        $check_sign=$this->getSign($arr,$keyValue);
        return $sign === $check_sign ? true : false;
    }


    //回调方法，把返回数据处理成统一规定返回
    public function response(){
        $data = parseData();
        // 进行签名验证
        $CheckSignStatus =  $this->checkSign($data,$this->config['mch_key']);
        if($CheckSignStatus){
            // 验签成功
            if($data['result_code'] == '200'){
                return true;
            }else{
                return false;
            }
        }else{
            // 失败
            return false;
        }
    }

}
